package zdream.rockchronicle.foes.mm;

import zdream.control.foe.mm.MegaMan;
import zdream.control.world.Ticker;
import zdream.rockchronicle.RockChronicle;
import zdream.rockchronicle.core.graphics.FoePainter;

/**
 * @author Zdream
 * @since 0.0.1
 * @date 2022-05-28
 */
public class MegaManPainter extends FoePainter {
	final MegaMan mm;

	public MegaManPainter(MegaMan mm) {
		super(mm);
		super.z = 1000;
		this.mm = mm;
		this.tickAutomatically = false;
		this.batch = RockChronicle.INSTANCE.graphics.batch;
	}

	/**
	 * 使用的 Sprite 的形态
	 */
	long attackRemain = 0; // TODO 攻击之后有一段时间还是举枪状态

	@Override
	public void draw(Ticker ticker) {
		tick(ticker);
		super.draw(ticker);
	}

	private void tick(Ticker ticker) {
		if (ticker.paused) {
			return;
		}

		long lDuration = ticker.durationInFrame;
		if (attackRemain > 0) {
			attackRemain = Math.max(0, (int) (attackRemain - lDuration));
		}

		// 是否硬直
		if (mm.motionModule.stiffness > 0) {
			if (mm.motionModule.slideDuration > 0) {
				setState("slide");
			} else {
				setState("stiffness");
			}
			tickFrame(ticker.delta);
			return;
		}

		// 攻击判定
		boolean attacking = mm.weaponModule.attacking;
		if (attacking) {
			attackRemain = 500;
		}

		// 是否在攀爬
		int climbing = mm.motionModule.climbing;
		if (climbing >= 0) {
			if (mm.motionModule.climbHaltRemain != 0) {
				setState("climb_attack");
				return;
			}

			if (climbing > 50) {
				setState("climb_top_1");
			} else if (climbing > 0) {
				setState("climb_top_0");
			} else {
				setState("climb");
			}

			if (mm.motionModule.climbDirection != 0) {
				tickFrame(ticker.delta);
			}
			return;
		}

		// 是否在滑铲
		if ("slide".equals(mm.currentPattern.name)) {
			setState("slide");
			tickFrame(ticker.delta);
			return;
		}

		// 是否在跳跃
		boolean inAir = mm.inAir;
		if (inAir) {
			boolean direction = mm.velocityY >= 0;
			String s1 = (direction) ? "jump" : "drop";
			String s2 = (direction) ? "jump_attack" : "drop_attack";

			if (attackRemain > 0) {
				if (s1.equals(select.getState())) {
					select.replaceState(s2);
				} else {
					setState(s2);
				}
			} else {
				if (s2.equals(select.getState())) {
					select.replaceState(s1);
				} else {
					setState(s1);
				}
			}

			tickFrame(ticker.delta);
			return;
		}

		int walking = mm.motionModule.walking;

		if (walking != 0) {
			if (attackRemain > 0) {
				if ("walk".equals(select.getState())) {
					select.replaceState("walk_attack");
				} else {
					setState("walk_attack");
				}
			} else {
				if ("walk_attack".equals(select.getState())) {
					select.replaceState("walk");
				} else {
					setState("walk");
				}
			}
		} else {
			if (attackRemain > 0) {
				setState("normal"); // attacking TODO
			} else {
				setState("normal");
			}

		}
		tickFrame(ticker.delta);
	}
}
